<template>
  <div class="org-member-tree h100">
    <!--    <div class="filter__box" v-if="isFilter">-->
    <div class="filter__box" v-if="isFilter && !editTree">
      <el-input
        placeholder="输入关键字过滤"
        size="mini"
        class="treeInput"
        v-model="filterText"
        clearable
      ></el-input>
    </div>
    <!--    带热搜索定位-->
    <div class="filter__box" v-if="editTree">
      <el-autocomplete
        class="inline-input"
        v-model="searchText"
        sizi="mini"
        :fetch-suggestions="querySearch"
        placeholder="请输入关键字搜索"
        :trigger-on-focus="false"
        @select="handleSelect"
        clearable
      ></el-autocomplete>
    </div>
    <!--    显示根节点按钮-->
    <div class="edit-tree-toolbar" v-if="rootNode">
      <div style="font-weight: bold">{{ this.customRootNode }}</div>
      <div class="edit-btn" v-if="rootNodeBtn">
        <template v-for="(i, index) in btnConfig">
          <el-button
            type="plain"
            class="btn-text-blue"
            size="mini"
            :key="index"
            v-if="showBtn(i.name)"
            :icon="i.icon"
            @click="i.methons"
            >{{ i.text }}</el-button
          >
        </template>
      </div>
    </div>
    <!-- 可编辑的树 -->
    <div
      class="tree__box"
      :style="{
        height: rootNode == true ? 'calc(100% - 90px)' : 'calc(100% - 60px)'
      }"
      v-if="editTree"
    >
      <el-tree
        class="filter-tree"
        :data="elTreeData"
        :props="props"
        :filter-node-method="filterNode"
        :expand-on-click-node="clickExpand"
        highlight-current
        :default-expand-all="defaultExpand"
        :node-key="nodeKey"
        :default-expanded-keys="expandKeys"
        @node-click="treeNodeClick"
        draggable
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, elTreeData }">
          <span>{{ elTreeData.classifyName }}</span>
          <span v-if="currentNode.id === elTreeData.id">
            <span>
              <el-button
                v-if="btnArr.indexOf('add') != -1"
                type="text"
                @click.native="() => TNodeAdd(node, elTreeData)"
                class="btnIcon"
                icon="el-icon-plus"
              ></el-button>
              <el-button
                v-if="btnArr.indexOf('edit') != -1"
                type="text"
                @click.native="() => TNodeEdit(node, elTreeData)"
                class="btnIcon"
                icon="el-icon-edit-outline"
              ></el-button>
              <el-button
                v-if="btnArr.indexOf('detail') != -1"
                type="text"
                @click.native="() => TNodeDetail(node, elTreeData)"
                class="btnIcon"
                icon="el-icon-document"
              ></el-button>
              <el-button
                v-if="btnArr.indexOf('delete') != -1"
                type="text"
                @click.native="() => TNodeDel(node, elTreeData)"
                class="btnIcon"
                icon="el-icon-delete"
              ></el-button>
            </span>
          </span>
        </span>
      </el-tree>
    </div>
    <!-- 不可编辑的非懒加载树 -->
    <div class="tree__box" v-if="!editTree && !lazy">
      <el-tree
        class="filter-tree"
        :data="elTreeData"
        :props="props"
        :filter-node-method="filterNode"
        :expand-on-click-node="clickExpand"
        highlight-current
        :default-expand-all="defaultExpand"
        :node-key="nodeKey"
        :auto-expand-parent="true"
        :default-checked-keys="defaultCheckedNode"
        :default-expanded-keys="expandKeys"
        @node-click="treeNodeClick"
        ref="tree"
      >
      </el-tree>
    </div>
    <!-- 不可编辑的懒加载树 -->
    <div class="tree__box" v-if="!editTree && lazy">
      <el-tree
        class="filter-tree"
        :data="elTreeData"
        :props="props"
        :load="loadNode"
        lazy
        :filter-node-method="filterNode"
        :expand-on-click-node="clickExpand"
        highlight-current
        :default-expand-all="defaultExpand"
        :node-key="nodeKey"
        :auto-expand-parent="true"
        :default-checked-keys="defaultCheckedNode"
        :default-expanded-keys="expandKeys"
        @node-click="treeNodeClick"
        ref="tree"
      >
      </el-tree>
    </div>
  </div>
</template>

<script>
import { accountTreeData } from "@/api/deviceAccount/deviceAccount.js";
import { deviceTreeData, queryDictDataSelect } from "@/api/common";
var actionMethos = null;
export default {
  props: {
    treeType: {
      type: String,
      default: ""
    },
    defaultProps: {
      type: Object,
      default: () => {
        return { children: "children", label: "label" };
      }
    },
    clickExpand: {
      type: Boolean,
      default: true
    },
    customRootNode: {
      type: String,
      default: ""
    },
    rootNodeBtn: {
      type: Boolean,
      default: true
    },
    rootNode: {
      type: Boolean,
      default: false
    },
    defaultExpand: {
      type: Boolean,
      default: false
    },
    defaultExpandKeys: {
      type: Array,
      default: () => {
        return [];
      }
    },
    nodeKey: {
      type: String,
      default: ""
    },
    isFilter: {
      type: Boolean,
      default: true
    },
    filterLabel: {
      type: String,
      default: ""
    },
    mySort: {
      type: Boolean,
      default: false
    },
    editTree: {
      type: Boolean,
      default: false
    },
    btnArr: {
      type: Array,
      default: []
    },
    lazy: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeConfig: {
        select: true,
        data: {} //JSON.parse(JSON.stringify(data))
      },
      btnConfig: [
        {
          name: "add",
          text: "根节点",
          icon: "el-icon-plus",
          methons: () => {
            this.addRoot();
          }
        }
      ],
      treeData:[],

      treeLists: [],
      defaultCheckedNode: [],
      navList: [],
      searchText: "",
      filterText: "",
      props: {},
      currentNode: {}, //当前节点
      //    filterInput:true,
      elTreeData: []
    };
  },
  computed: {
    expandKeys() {
      if (this.defaultExpandKeys.length) {
        return this.defaultExpandKeys;
      } else if (this.elTreeData.length) {
        let id = this.nodeKey || "id";
        return [this.elTreeData[0][id]];
      } else {
        return [];
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterLabel(val) {
      this.$refs.tree.filter(val);
    },
    isFilter(val) {
      this.isFilter = val;
    },
    mySort(val) {
      this.mySort = val;
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // this.elTreeData = JSON.parse(JSON.stringify(this.treeData));
      this.props = Object.assign({}, this.defaultProps);
      switch(this.treeType){
        case "equipment":
          actionMethos = deviceTreeData;
          break;
        // case "depart":
        //   actionMethos = getDepartmentTree;
        //   break;
        // case "asset":
        //   actionMethos = getAssetTypeTree;
        //   break;

      }
      this.getTreeData();

    },
        //获取组织树数据
    getTreeData() {
      let params = {
        parentId: "0"
      };
      //得到组织树的数据
      actionMethos(params)
        .then(res => {
          let zsjOrg = [];
          for (let i = 0; i < res.data.length; i++) {
            zsjOrg.push(res.data[i]);
          }
          this.treeData = res.data;
          this.elTreeData = res.data;
          this.orgCode = zsjOrg[0].id;
          this.defaultExpandKeys.push(zsjOrg[0].id);
          this.setTreeData(zsjOrg);
          this.setSelcetData();
        })
        .catch(res => {
          this.setTreeData([]);
          this.$message.error(res.description);
        });
    },
    addRoot() {
      this.$emit("addRootNode");
    },
    //显示按钮
    showBtn(btn) {
      return this.btnArr.indexOf(btn) != -1;
    },
    //新增
    querySearch(queryString, cb) {
      let allTreeData = this.treeData;
      //新增
      let treeList = allTreeData;
      this.treeLists = allTreeData;
      let arr = treeList || [];
      let navArr = [];
      const f = function(arr) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          let children = item.children;
          if (children && children.length) {
            f(children);
          } else {
            navArr.push({
              value: item.classifyName,
              ...item
            });
          }
        }
      };
      f(arr);
      this.navList = [...navArr];
      let restaurants = [...this.navList];
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 500 * Math.random());
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    getParentNodes(arr1, id) {
      // 声明数据集合
      var temp = [];
      // 声明递归函数
      var forFn = function(arr, id) {
        // 遍历树
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];
          if (item.id === id) {
            // 查找到指定节点并加入集合
            temp.push(item);
            // 查找其父节点
            forFn(arr1, item.parentId);
            // 不必向下遍历，跳出循环
            break;
          } else {
            if (item.children) {
              // 向下查找到id
              forFn(item.children, id);
            }
          }
        }
      };
      // 调用函数
      forFn(arr1, id);
      // 返回结果
      return temp;
    },
    handleSelect(item) {
      let currentId = item.id;
      let parentArr = this.getParentNodes(this.treeLists, currentId);
      let ids = [];
      parentArr.map(item => {
        ids.push(item.id);
      });
      this.expandKeys = ids;
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(currentId);
      });
      this.treeNodeClick(item);
    },

    //新增字节点
    TNodeAdd(node, data) {
      this.$emit("add", data);
      /* this.show = true;
      let { id, orgName, parentId, parentName } = data;
      this.editFormData = {
        orgName: "",
        parentId: id,
        parentName: orgName
      };*/
    },
    //编辑
    TNodeEdit(node, data) {
      this.$emit("edit", data);
      /*this.show = true;
      this.editFormData = Object.assign({}, data);*/
    },
    //删除
    TNodeDel(node, data) {
      this.$confirm(
        "此操作将删除【" + data.classifyName + "】, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$emit("delete", data.id);
          this.$refs.tree.remove(data);
        })
        .catch(e => {});
    },
    //详情
    TNodeDetail(node, data) {
      this.$emit("detail", data);
    },
    filterNode(value, data) {
      if (!value) return true;
      let label = data[this.props.label];
      return label.indexOf(value) !== -1;
    },
    treeNodeClick(node) {
      this.currentNode = JSON.parse(JSON.stringify(node));
      this.$emit("handleClickTree", node);
    },
    /*  loadNode(node) {
      this.$emit("loadNode", node);
    },*/
    /*   setNoNode() {
      this.$refs.tree.setCurrentKey(null);
    },*/
    //默认进来加载数据
    loadNode(node, resolve) {
      //如果展开第一级节点，从后台加载一级节点列表
      if (node.level == 0) {
        this.loadfirstnode(resolve);
      }
      //如果展开其他级节点，动态从后台加载下一级节点列表
      if (node.level >= 1) {
        this.node = node;
        this.resolve = resolve;
        this.loadchildnode(node, resolve);
      }
    },
    //加载第一级节点
    loadfirstnode(resolve) {
      let params = {
        parentId: "0"
      };
      //得到组织树的数据
      accountTreeData(params)
        .then(res => {
          res.data.map(item => {
            item.isLeaf =
              item.haveChildren === 0 ||
              item.haveChildren == "null" ||
              item.haveChildren == "undefined"
                ? true
                : false;
          });
          return resolve(res.data);
        })
        .catch(res => {
          this.$message.error(res.description);
        });
    },
    //加载节点的子节点集合
    loadchildnode(node, resolve) {
      let params = {
        parentId: node.data.id
      };
      //得到组织树的数据
      accountTreeData(params)
        .then(res => {
          res.data.map(item => {
            item.isLeaf =
              item.haveChildren === 0 ||
              item.haveChildren == "null" ||
              item.haveChildren == "undefined"
                ? true
                : false;
          });
          return resolve(res.data);
        })
        .catch(res => {
          this.$message.error(res.description);
        });
    },
    getCurrentKey() {
      return this.$refs.tree.getCurrentKey();
    },
    //设置树数据
    setTreeData(data) {
      this.$set(this, "elTreeData", data);
      setTimeout(() => {
        this.$refs.tree.setCurrentKey(this.currentNode.id);
      });
    },
    setSelcetData(selectedNode) {
      setTimeout(() => {
        if (selectedNode) {
          //新增树节点之后，更新树的数据，默认选中当前选中的节点
          this.$refs.tree.setCurrentKey(selectedNode.id); //设置当前选择的节点
          this.treeNodeClick(selectedNode);
        } else {
          let node = this.elTreeData[0];
          this.$refs.tree.setCurrentKey(node.id); //设置当前选择的节点
          this.treeNodeClick(node);
        }
      }, 0);
    }
  }
};
</script>

<style>
.org-member-tree .el-tree-node__content {
  border-left: 3px solid transparent;
}
.org-member-tree
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  /* background-color: #e9f1fe !important;
  /*border-left: 3px solid #2c77f4;*/
  /* color: #2c77f4;  */
}
</style>

<style lang="less" scoped>
.org-member-tree {
  .filter__box {
    padding: 10px;
  }
  .inline-input {
    width: 99%;
  }
  .treeInput {
    width: 99%;
  }
  .tree__box {
    height: calc(100% - 60px);
    overflow: auto;
    padding-top: 5px;
  }
  .buttonFlag {
    background: #2c77f4;
    color: #fff;
    border-radius: 3px;
    padding: 0 5px;
    font-size: 12px;
  }
  .edit-tree-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .el-button {
      margin-right: 10px;
      margin-left: 0px;
    }
  }
}
</style>
